<!-- 这是商品详情的组件 -->
<template>
  <div class="apps">
    <!-- 轮播图 -->
    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="(image, index) in images" :key="index">
        <img v-lazy="image" :style="{  borderColor: '#ccc'}" class="imgs" @click="Preview()" />
      </van-swipe-item>
    </van-swipe>
    <div v-for="item in catelist" :key="item.id" class="cards">
      <div class="card">
        <div class="phop">{{item.title}}</div>
        <van-divider :style="{  borderColor: '#ccc'}"></van-divider>
        <div class="pices">
          市场价:
          <s>￥{{item.market_price}}</s>
          销售价:
          <b>￥{{item.sell_price}}</b>
        </div>
        <div class="number">
          购买数量：
          <van-stepper v-model="steppervalue" @change="getInputVal"/>
        </div>
        <van-button size="normal" type="info">立即购买</van-button>
        <van-button size="normal" type="danger" @click="addCart(item)">加入购物车</van-button>
      </div>
      <div class="card">
        <div class="canshu">商品参数</div>
        <van-divider :style="{  borderColor: '#ccc'}"></van-divider>
        <div class="goods">
          <p>商品货号:{{item.goods_no}}</p>
          <p>库存情况:{{item.stock_quantity}}</p>
          <p>上架时间:{{item.add_time.split('T')[0]}}</p>
          <van-divider :style="{  borderColor: '#ccc'}"></van-divider>
          <van-button
            plain
            hairline
            type="info"
            block
            @click="gocatelist(item.id)"
            class="btns"
          >图文介绍</van-button>
          <van-button
            plain
            hairline
            type="danger"
            block
            @click="gocomment(item.id)"
            class="btns"
          >商品评论</van-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { ImagePreview } from 'vant'
// 按需导入mapState函数，将所需数据映射为计算属性使用
import { mapState, mapMutations } from 'vuex'
export default {
  data () {
    return {
      steppervalue: 1,
      catelist: [],
      images: [],
      // imgPreviewDialog:'',
      arr: []
    }
  },
  created () {
    // 一开始加载页面时，car是一个空数组  从localStorage中获取
    this.saveInCar()

    this.getcate()
    this.getimglist()
  },
  methods: {
    ...mapMutations(['saveInCar', 'getCartCount']),
    // 点击+-h号时触发
    getInputVal (val) {
      this.steppervalue = val
    },
    // 点击'添加到购物车'按钮时触发 ,将当前商品id和购买数量添加到共享数据car数组中
    addCart (goodsInfo) {
      console.log(this.car)
      const obj = {
        id: goodsInfo.id,
        count: this.steppervalue
      }
      // 循环car数组，根据id，查询当前商品是否已经存在于car数组中
      const index = this.car.findIndex(item => {
        return item.id === obj.id
      })
      console.log(index)
      // 说明当前要添加的商品不存在于car数组中
      if (index === -1) {
        // 将当前商品添加到car数组中
        this.car.push(obj)
        // 同时，将car数组存储到localStorage中————防止关闭浏览器后数据消失
        window.localStorage.setItem('car', JSON.stringify(this.car))

        // 获取购物车商品的数量
        this.getCartCount()
      } else {
        // 说明当前要添加的商品已经存在于car数组中
        // 将car数组中对应数据的count属性值加1
        this.car[index].count += this.steppervalue
        // 同时，将car数组存储到localStorage中————防止关闭浏览器后数据消失
        window.localStorage.setItem('car', JSON.stringify(this.car))

        // 获取购物车商品的数量
        this.getCartCount()
      }

      // 提示用户添加成功
      this.$toast.success('加入购物车成功')
    },
    async getcate () {
      var ids = window.location.hash.split('=')
      var id = ids[1]
      const { data: res } = await this.$http.get('/api/goods/getinfo/' + id)
      this.catelist = res.message
    },
    async getimglist () {
      var ids = window.location.hash.split('=')
      var id = ids[1]
      const { data: res } = await this.$http.get('/api/getthumimages/' + id)
      // console.log(res)
      this.images = res.message
      res.message.forEach(item => {
        this.arr.push(item.src)
        console.log(this.arr)
      })
    },
    gocatelist (id) {
      this.$router.push('/catelist?id=' + id)
    },
    gocomment (id) {
      this.$router.push('/catelcomment?id=' + id)
    },
    Preview () {
      ImagePreview({
        images: this.arr,
        closeable: true
      })
    }
  },
  // 计算属性
  computed: {
    ...mapState(['car'])
  }
}
</script>
<style scoped lang="less">
.apps {
  margin: 60px 0;
}
.van-swipe {
  height: 50vw;
  margin: 10px 20px;
  text-align: center;
  border: 1px solid #ccc;
  border-radius: 8px;
}
.card {
  border: 1px solid #ccc;
  border-radius: 8px;
  margin-bottom: 10px;
  padding: 30px;
  .number {
    padding: 0 5px;
    color: #8f8f94;
    margin-bottom: 15px;
    .van-stepper {
      display: inline;
      vertical-align: middle;
    }
  }
  .van-button {
    margin-right: 10px;
  }
}
.btns {
  margin-top: 10px;
}
.pices {
  padding: 20px 5px;
  color: #8f8f94;
  b {
    color: red;
  }
}
.canshu {
  font-size: 18px;
}
.phop {
  font-size: 18px;
}
.goods {
  color: #8f8f94;
}
.cards {
  padding: 20px;
}
.imgs {
  height: 100%;
}
</style>
